<?php
namespace App\Service;

class Baidu
{
	const API_ADDR = "http://api.map.baidu.com";
	private $ak = 'dGtn9hZL8HOjiu0ojXGB9TAYG2LKN4lh';
	private $sk = 'WuCPRNuZRvQCGXVsxYQWFyb8r5pNmOFF';

	public function __construct($ak = '', $sk = '')
	{
		if (!empty($ak) && !empty($sk)) {
			$this->ak = $ak;
			$this->sk = $sk;
		}
	}

	public function geocoder($lot, $lng, $output = 'json')
	{
		$uri = '/geocoder/v2/';

		$param = [
			'location'	=>	"{$lot},{$lng}",
			'output'	=>	$output,
			'ak'	=>	$this->ak,
		];
		$url = self::API_ADDR . $uri  . "?" . http_build_query($param);

		$sn = $this->caculateAKSN($this->ak, $this->sk, $uri, $param);
		$api = $url ."&sn={$sn}";
		$data = file_get_contents($api);

		$data = json_decode($data, true);
		return $data;
	}

	public function caculateAKSN($ak, $sk, $url, $param, $method = 'GET')
	{  
	    if ($method === 'POST'){  
	        ksort($param);  
	    }  
	    $querystring = http_build_query($param);  
	    return md5(urlencode($url.'?'.$querystring.$sk));  
	}
}